import React, { useEffect, useState } from "react";
import '../../appcommon.css';
import styles from './mywallet.module.css';
import { useDispatch } from "react-redux";
import { Dialog, DotLoading, Mask } from "antd-mobile";
import { saveEvent } from "@/store/actions/saveEvent";
import { useHistory } from "react-router-dom/cjs/react-router-dom.min";

import icon_right_black from '@/assets/icon_right_black.png'

import NavigateBar from "@/components/NavigateBar";
import { getUserWallet, setWalletName } from "@/store/actions/user";
import { getManageWalletCoinType, getUserInfo } from "@/utils/storage";
import DialogInput from "@/components/Input/dialogInput";
import { LangThai } from "@/utils/langThai";


/**
 * 登录页
 */
export default function MyWalletManage() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(true);

    // 当前 账号
    const [curAccount, setCurAccount] = useState("")

    // 当前 对话框钱包编辑内容
    const [curWalletEditName, setCurWalletEditName] = useState("")

    // 当前 对话框钱包编辑内容
    const [curWalletEditNameResult, setCurWalletEditNameResult] = useState("")


    // 当前 钱包
    const [curWallet, setCurWallet] = useState({})

    // 文案翻译
    const [curLang, setCurLang] = useState(LangThai);

    // 获取 Redux 分发器
    const dispatch = useDispatch()

    //router
    const history = useHistory()

    // 当前输入内容
    let curInputWalletName = "";

    //清空登录信息
    useEffect(() => {
        //关闭loading
        setMaskVisible(false);

        // 获取账号信息
        let userInfo = getUserInfo();
        setCurAccount(userInfo.mobile || "");

        // 获取币种信息
        let coninType = getManageWalletCoinType();
        doGetUserWallet(coninType);

        //打点
        doHitEvent("MY_WALLET_LIST_START")

        return () => {
            //打点
            doHitEvent("MY_WALLET_LIST_END")
        }
    }, [])

    // 获取钱包信息 返回
    const onDoGetUserWalletCallback = (success, data) => {
        //关闭loading
        setMaskVisible(false)
        console.log('获取币种信息接口 返回: ' + success);

        if (success && data) {
            // 处理流程业务
            // {
            //     "walletId": 47,
            //     "address": "132A3kUhBh9jGHM6m9YAvwZULi5NXZg6cR",
            //     "name": null,
            //     "coinUnit": "BTC",
            //     "balance": 0
            // }

            let name = data.name || "";
            let coinUnit = data.coinUnit || "";
            if (name.length <= 0) {
                data.name = coinUnit;
            }

            // 保存
            setCurWallet(data);
            setCurWalletEditName(data.name);

            curInputWalletName = data.name;
        }
    };

    // 设置用户钱包名称 返回
    const onDoStWalletNameCallback = (success, data) => {
        //关闭loading
        setMaskVisible(false)
        console.log('设置用户钱包名称 返回: ' + success);

        if (success) {
            // 处理流程业务

            // 获取币种信息
            let coninType = getManageWalletCoinType();
            doGetUserWallet(coninType);
        }
    };

    const onHandleDialogInputChanged = (text) => {
        setCurWalletEditNameResult((prevText) => {
            return text;
        });

        setCurWalletEditName((prevText) => {
            return text;
        });

        curInputWalletName = text;
    };

    // 点击修改 钱包名称
    const onHandleEditWalletName = () => {
        console.log('点击修改 钱包名称');

        Dialog.confirm({
            title: curLang.myWalletManageWalletName,
            content: <DialogInput defaultValue={curWalletEditName} onInputChanged={(text) => {
                onHandleDialogInputChanged(text);
            }} />,
            cancelText: curLang.myWalletManageCancel,
            confirmText: curLang.myWalletManageConfirm,
            onConfirm: () => {
                console.log("点击了确认：" + curInputWalletName);
                // 设置 钱包名称
                doSetWalletName();
            }
        });
    };


    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 获取钱包信息
    const doGetUserWallet = async (coinType) => {
        console.log("doGetUserWallet: ");

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getUserWallet(coinType, onDoGetUserWalletCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 设置用户钱包名称
    const doSetWalletName = async () => {
        console.log("doStWalletName: " + curInputWalletName);

        if (!curInputWalletName || (curInputWalletName.length <= 0)) {
            return;
        }

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = setWalletName(curInputWalletName, curWallet.walletId, onDoStWalletNameCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }


    return (
        <div className='pageRoot pageBackgroundColorGray'>
            <NavigateBar theme="white" showLogout={false} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}>Manage</NavigateBar>

            {/* 使用添加 home screen bar */}
            {/* <AddFavorite onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

            <div className="pageContentColumnFull">
                {/* 账号名称 */}
                <div className={styles.myWalletManageItemTextRow}>
                    <div className={styles.myWalletManageItemTitle}>{curLang.myWalletManageIdentityWalletUserName}</div>
                    <div className={styles.myWalletManageItemDetail}>{curAccount}</div>
                </div>

                <div className={styles.myWalletManageItemTextRow}>
                    {/* 钱包地址 */}
                    <div className={styles.myWalletManageItemTitle}>{curLang.myWalletManageWalletAddress}</div>
                    <div className={styles.myWalletManageItemDetail}>{curWallet.address}</div>
                    <div className={styles.myWalletManageBottomLine}></div>

                    {/* 钱包名称 */}
                    <div className={styles.myWalletManageItemEditWalletNameRow}>
                        <div className={styles.myWalletManageItemTitle}>{curLang.myWalletManageWalletName}</div>
                        <div className={styles.myWalletManageItemWalletName} onClick={onHandleEditWalletName}>{curWallet.name}</div>
                        <img className={styles.myWalletManageItemExtIcon} alt="" src={icon_right_black} onClick={onHandleEditWalletName} />
                    </div>
                </div>
            </div>

            {/* 底部 margin */}
            <div className="pageBottomEdge"></div>

            {/* load mask */}
            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="pageLoadingOverlayContent">
                    <span style={{ fontSize: 24, color: '#3498DB' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div >
    )
}